package com.example.lj.uav.view;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.PhotoAdapter;
import com.example.lj.uav.utils.OnUIUtils;
import com.example.lj.uav.view.base.BaseActivity;
import com.example.lj.uav.widget.ViewPagerFixed;
import com.loc.r;
import com.mapbox.api.directions.v5.AutoValueGson_DirectionsAdapterFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import dji.common.camera.SettingsDefinitions;
import dji.common.error.DJICameraError;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.log.DJILog;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;
import dji.sdk.media.DownloadListener;
import dji.sdk.media.FetchMediaTaskScheduler;
import dji.sdk.media.MediaFile;
import dji.sdk.media.MediaManager;

public class PhotoBrowserActivity extends BaseActivity implements ViewPager.OnPageChangeListener, View.OnClickListener ,Handler.Callback {
    private ViewPagerFixed mVp;
    private TextView mTvHint;
    private LinearLayout mLl;

    private List<MediaFile> files;
    private int mPosition;
    private PhotoAdapter adapter;
    private Handler mHandler;
    private PopupWindow popupWindowList;
    private PopupWindow popupWindowMenu;
    private ImageView mIvList;
    private ImageView mIvMenu;
    private Camera camera;
    private int cameraPosition;
    private ProgressBar mPb;
    private String[] downloadList;
    private ImageView mIvDownload;
    private MediaManager manager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_browser);
        initView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        mHandler = new Handler(this);
        files = MyApplication.getSavedMediaFiles();
        mPosition = intent.getIntExtra("position", 0);
        cameraPosition = intent.getIntExtra("camera",0);
        BaseProduct product = MyApplication.getProductInstance();
        if (product!=null){
            List<Camera> cameras = product.getCameras();
            camera = cameras.get(cameraPosition);
            camera.setMode(SettingsDefinitions.CameraMode.MEDIA_DOWNLOAD, new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError djiError) {
                    if (djiError!=null){
                        OnUIUtils.setToast(djiError.toString());
                    }
                }
            });
            manager = camera.getMediaManager();
            if (manager!=null){
                FetchMediaTaskScheduler scheduler = manager.getScheduler();
                adapter = new PhotoAdapter(this, files,mHandler,scheduler,manager);
            }
        }

        mVp.setAdapter(adapter);
        mVp.setCurrentItem(mPosition);
        mVp.addOnPageChangeListener(this);
    }

    private void initView() {
        mVp = findViewById(R.id.vp_photo);
        mTvHint = findViewById(R.id.tv_photo_hint);
        mLl = findViewById(R.id.ll_media_browser_title_bar);
        mIvDownload = findViewById(R.id.iv_media_browser_download);
        findViewById(R.id.iv_media_browser_back).setOnClickListener(this);
        findViewById(R.id.iv_media_browser_list).setOnClickListener(this);
        findViewById(R.id.iv_media_browser_delete).setOnClickListener(this);
        mIvDownload.setOnClickListener(this);
        findViewById(R.id.iv_media_browser_menu).setOnClickListener(this);
        mIvList = findViewById(R.id.iv_media_browser_list);
        mIvMenu = findViewById(R.id.iv_media_browser_menu);
        mPb = findViewById(R.id.pb_media_download_progress);
        //
        File file = new File(Environment.getExternalStorageDirectory()+"/UAV/MEDIA");
        if (file.exists()){//判断当前mediafile有没有被下载
            downloadList = file.list();
            for (int i = 0; i < downloadList.length; i++) {
                if (downloadList[i].equals(files.get(mPosition))){
                    mIvDownload.setVisibility(View.GONE);
                    break;
                }
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mPosition = position;
        mTvHint.setText(mPosition + "/" + files.size());
        File file = new File(Environment.getExternalStorageDirectory()+"/UAV/MEDIA");
        if (file.exists()){//判断当前mediafile有没有被下载
            downloadList = file.list();
            for (int i = 0; i < downloadList.length; i++) {
                if (downloadList[i].equals(files.get(mPosition))){
                    mIvDownload.setVisibility(View.GONE);
                    return;
                }
            }
        }
        mIvDownload.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_media_browser_back:
                PhotoBrowserActivity.this.finish();
                break;
            case R.id.iv_media_browser_list:
                showListPopupWindow();
                break;
            case R.id.iv_media_browser_delete:
                if (camera==null){
                    return;
                }
                final MediaManager manager = camera.getMediaManager();
                if (manager==null){
                    return;
                }
                List<MediaFile> list = new ArrayList<>();
                list.add(files.get(mPosition));
                manager.deleteFiles(list, new CommonCallbacks.CompletionCallbackWithTwoParam<List<MediaFile>, DJICameraError>() {
                    @Override
                    public void onSuccess(List<MediaFile> failedFiles, DJICameraError djiCameraError) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                OnUIUtils.setToast("删除成功");
                                files.remove(mPosition);
                                adapter.notifyDataSetChanged();
                                OnUIUtils.setTextView(mTvHint,mPosition+"/"+files.size());
                            }
                        });
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        OnUIUtils.setToast(djiError.toString());
                    }
                });
                break;
            case R.id.iv_media_browser_download:

                final MediaFile file = files.get(mPosition);
                String folderUrl = Environment.getExternalStorageDirectory()+"UAV/MEDIA";
                final File storageFolder = new File(folderUrl);
                if (!storageFolder.exists()){
                    storageFolder.mkdir();
                }
                downloadFileByIndex(mPosition,storageFolder);
//                camera.setMode(SettingsDefinitions.CameraMode.MEDIA_DOWNLOAD, new CommonCallbacks.CompletionCallback() {
//                    @Override
//                    public void onResult(DJIError djiError) {
//                        if (djiError==null){
//                            file.fetchFileData(storageFolder, null, new DownloadListener<String>() {
//                                @Override
//                                public void onStart() {
//                                    OnUIUtils.setViewVisibility(mPb, View.VISIBLE);
//                                }
//
//                                @Override
//                                public void onRateUpdate(long l, long l1, long l2) {
//
//                                }
//
//                                @Override
//                                public void onProgress(long total, long current) {
//                                    int progress = (int) (current/total*100);
//                                    OnUIUtils.setProgressBarProgress(mPb,progress);
//                                }
//
//                                @Override
//                                public void onSuccess(String s) {
//                                    OnUIUtils.setViewVisibility(mPb, View.GONE);
//                                    OnUIUtils.setToast("下载成功");
//                                }
//
//                                @Override
//                                public void onFailure(DJIError djiError) {
//                                    OnUIUtils.setViewVisibility(mPb, View.GONE);
//                                    OnUIUtils.setToast("下载失败");
//                                }
//                            });
//                        }else{
//                            OnUIUtils.setToast(djiError.toString());
//                        }
//                    }
//                });
                break;
            case R.id.iv_media_browser_menu:
                showMenuPopupWindow();
                break;
            case R.id.tv_media_menu_edit:
                break;
            case R.id.tv_media_menu_edit_by:
                break;
            case R.id.tv_media_menu_info:
                break;
            case R.id.tv_media_menu_open_by:
                break;
        }
    }

    private void showMenuPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_media_menu,null);
        view.findViewById(R.id.tv_media_menu_edit).setOnClickListener(this);
        view.findViewById(R.id.tv_media_menu_edit_by).setOnClickListener(this);
        view.findViewById(R.id.tv_media_menu_info).setOnClickListener(this);
        view.findViewById(R.id.tv_media_menu_open_by).setOnClickListener(this);
        if (popupWindowMenu==null){
            popupWindowMenu = new PopupWindow(view,300,RadioGroup.LayoutParams.WRAP_CONTENT,true);
        }
        popupWindowMenu.setTouchable(true);
        popupWindowMenu.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        popupWindowMenu.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_grey_bg));
        popupWindowMenu.showAsDropDown(mIvMenu,0,-60);
    }

    private void showListPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_media_list,null);
        RadioGroup rg = view.findViewById(R.id.rg_media_list);
        RadioButton rb1 = view.findViewById(R.id.rb_media_list_name);
        RadioButton rb2 = view.findViewById(R.id.rb_media_list_date);
        RadioButton rb3 = view.findViewById(R.id.rb_media_list_size);
        RadioButton rb4 = view.findViewById(R.id.rb_media_list_type);
        LinearLayout ll = view.findViewById(R.id.ll_media_list_order);
        final CheckBox cb = view.findViewById(R.id.cb_media_list_order);
        Drawable drawable1 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable2 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable3 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable4 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        drawable1.setBounds(0,0,34,34);
        drawable2.setBounds(0,0,34,34);
        drawable3.setBounds(0,0,34,34);
        drawable4.setBounds(0,0,34,34);
        rb1.setCompoundDrawables(null,null,drawable1,null);
        rb2.setCompoundDrawables(null,null,drawable2,null);
        rb3.setCompoundDrawables(null,null,drawable3,null);
        rb4.setCompoundDrawables(null,null,drawable4,null);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_media_list_name:
                        listByName();
                        break;
                    case R.id.rb_media_list_date:
                        listByTime();
                        break;
                    case R.id.rb_media_list_size:
                        listBySize();
                        break;
                    case R.id.rb_media_list_type:
                        listByType();
                        break;
                }
                popupWindowList.dismiss();
            }
        });
        Drawable drawable5 = getResources().getDrawable(R.drawable.selector_media_check_box);
        drawable5.setBounds(0,0,34,34);
        cb.setCompoundDrawables(null,null,drawable5,null);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    Toast.makeText(PhotoBrowserActivity.this, "checked", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(PhotoBrowserActivity.this, "unchecked", Toast.LENGTH_SHORT).show();
                }
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb.setChecked(!cb.isChecked());
            }
        });
        if (popupWindowList==null){
            popupWindowList = new PopupWindow(view,300,RadioGroup.LayoutParams.WRAP_CONTENT,true);
        }
        popupWindowList.setTouchable(true);
        popupWindowList.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        popupWindowList.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_grey_bg));
        popupWindowList.showAsDropDown(mIvList,0,-60);
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what){
            case 0:
                if (mLl.getVisibility()==View.INVISIBLE){
                    ObjectAnimator animator = ObjectAnimator.ofFloat(mLl,"translationY",-mLl.getHeight(),0);
                    animator.setDuration(300);
                    animator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {
                            mLl.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {

                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {

                        }
                    });
                    animator.start();
                }else{
                    ObjectAnimator animator = ObjectAnimator.ofFloat(mLl,"translationY",0,-mLl.getHeight());
                    animator.setDuration(300);
                    animator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            mLl.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {

                        }
                    });
                    animator.start();
                }
                break;
            case 1:
                MediaManager manager = camera.getMediaManager();
                if (manager.isVideoPlaybackSupported()){
                    Intent intent = new Intent(PhotoBrowserActivity.this,MediaPlayerActivity.class);
                    intent.putExtra("media",files.get(mPosition));
                    intent.putExtra("camera",cameraPosition);
                    startActivity(intent);
                }else{
                    showToast("不支持视频回放");
                }
                break;
        }
        return false;
    }

    private void listByName() {
        if (files.size()>0){
            Collections.sort(files, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    String name1 = mediaFile.getFileName();
                    String name2 = t1.getFileName();
                    int a = Integer.parseInt(name1.substring(4,name1.length()));
                    int b = Integer.parseInt(name2.substring(4,name2.length()));
                    long diff = a-b;
                    if (diff>0){
                        return 1;
                    }else if (diff<0){
                        return -1;
                    }
                    return 0;
                }
            });
            mVp.setCurrentItem(0);
            mPosition = 0;
            adapter.notifyDataSetChanged();
        }
    }

    private void listByTime(){
        if (files.size()>0){
            Collections.sort(files, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    long diff = mediaFile.getTimeCreated()-t1.getTimeCreated();
                    if (diff>0){
                        return 1;
                    }else if (diff<0){
                        return -1;
                    }
                    return 0;
                }
            });
            mVp.setCurrentItem(0);
            mPosition = 0;
            adapter.notifyDataSetChanged();
        }
    }

    private void listBySize(){
        if (files.size()>0){
            Collections.sort(files, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    long size1 = mediaFile.getFileSize();
                    long size2 = t1.getFileSize();
                    long diff = size1-size2;
                    if (diff>0){
                        return 1;
                    }else if (diff<0){
                        return -1;
                    }
                    return 0;
                }
            });
            mVp.setCurrentItem(0);
            mPosition = 0;
            adapter.notifyDataSetChanged();
        }
    }

    private void listByType(){
        if (files.size()>0){
            Collections.sort(files, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    MediaFile.MediaType type1 = mediaFile.getMediaType();
                    MediaFile.MediaType type2 = t1.getMediaType();
                    long diff = type1.value()-type2.value();
                    if (diff>0){
                        return 1;
                    }else if (diff<0){
                        return -1;
                    }
                    return 0;
                }
            });
            mVp.setCurrentItem(0);
            mPosition = 0;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    private void downloadFileByIndex(final int index,File destDir){
        if ((files.get(index).getMediaType() == MediaFile.MediaType.PANORAMA)
                || (files.get(index).getMediaType() == MediaFile.MediaType.SHALLOW_FOCUS)) {
            return;
        }

        files.get(index).fetchFileData(destDir, null, new DownloadListener<String>() {
            @Override
            public void onFailure(DJIError error) {
                OnUIUtils.setViewVisibility(mPb, View.GONE);
                OnUIUtils.setToast("Download File Failed" + error.getDescription());
//                currentProgress = -1;
            }

            @Override
            public void onProgress(long total, long current) {
            }

            @Override
            public void onRateUpdate(long total, long current, long persize) {
                int tmpProgress = (int) (1.0 * current / total * 100);
//                if (tmpProgress != currentProgress) {
                    OnUIUtils.setProgressBarProgress(mPb,tmpProgress);
//                    currentProgress = tmpProgress;
//                }
            }

            @Override
            public void onStart() {
//                currentProgress = -1;
                OnUIUtils.setViewVisibility(mPb, View.VISIBLE);
            }

            @Override
            public void onSuccess(String filePath) {
                OnUIUtils.setViewVisibility(mPb, View.GONE);
                OnUIUtils.setToast("Download File Success" + ":" + filePath);
//                currentProgress = -1;
            }
        });
    }


}
